package com.example.sunflowers.ui.viewpage

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import cn.trans88.taxiappkotlin.ext.logd
import cn.trans88.taxiappkotlin.ext.loge
import com.example.sunflowers.R
import com.example.sunflowers.adapters.GardenPlantingAdapter
import com.example.sunflowers.adapters.PLANT_LIST_PAGE_INDEX
import com.example.sunflowers.databinding.FragmentGardenBinding
import com.example.sunflowers.viewmodels.GardenPlantingListViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class GardenFragment : Fragment() {

    private lateinit var binding:FragmentGardenBinding

    private val viewModel:GardenPlantingListViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        "gardenFragment onCreate".logd()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        "gardenFragment onCreateView".logd()
        binding = FragmentGardenBinding.inflate(inflater,container,false)
        val adapter =  GardenPlantingAdapter()
        binding.gardenList.adapter = adapter
        binding.addPlant.setOnClickListener {
            navigateToPlantListPage()
        }

        subscribeUi(adapter, binding)
        // Inflate the layout for this fragment
        return binding.root
    }

    private fun subscribeUi(adapter: GardenPlantingAdapter,binding: FragmentGardenBinding){
        viewModel.plantAndGardenPlantings.observe(viewLifecycleOwner){result ->
            binding.hasPlantings = result.isNotEmpty()
            "result is not empty:${result.isNotEmpty()}".loge()
            adapter.submitList(result){
                //此时，应该绘制内容
                activity?.reportFullyDrawn()
            }
        }
    }


    private fun navigateToPlantListPage(){
        requireActivity().findViewById<ViewPager2>(R.id.view_pager).currentItem = PLANT_LIST_PAGE_INDEX
    }

    override fun onResume() {
        super.onResume()
        "gardenFragment onResume".logd()
    }

}